const {
    JSDOM
} = require('jsdom')
const zoroDB = require('../util/zoroDB')
const logger = require('log4js').getLogger()

var isDoing = false
var lastTime = 0;

exports.start = () => {
    if (isDoing) {
        if (new Date().getTime() - lastTime <= 1800000)
            return;
        logger.debug('[' + __filename + ':' + __line + ']', '超时重启任务')
    }
    isDoing = true;
    lastTime = new Date().getTime();
    new Promise(resolve => {
        zoroDB.query('select * from url where title is null', [], (err, rows, fields) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                isDoing = false;
                return
            }
            if (rows.length > 0) {
                resolve(rows[0])
            } else {
                zoroDB.query('select * from url order by rand() limit 1', [], (err, rows, fields) => {
                    if (err) {
                        logger.error('[' + __filename + ':' + __line + ']', err)
                        isDoing = false;
                        return
                    }
                    resolve(rows[0])
                })
            }
        })
    }).then(url => {
        require('../util/getHtml')({
            url: url.url
        }).then(html => {
            require('../dao/wordDao').select({}, words => {
                var promiseList = [];
                promiseList.push(new Promise(resolve => {
                    var dom = new JSDOM(html);
                    var title = '';
                    if (dom.window.document.querySelector('title')) {
                        title = dom.window.document.querySelector('title').textContent
                    }
                    if (!title) {
                        if (!!url.title) {
                            resolve(true)
                            return
                        }
                        title = '获取title失败';
                    }
                    logger.debug('[' + __filename + ':' + __line + ']', 'url = ' + url.url, 'title = ' + title)
                    zoroDB.query('update url set title=? where id=?', [title, url.id], (err, result) => {
                        if (err) {
                            logger.error('[' + __filename + ':' + __line + ']', err)
                        }
                        resolve(!url.title)
                    })
                }))
                // promiseList.push(new Promise(resolve => {
                //   zoroDB.query('insert into cache values(?,?,?,?)', [null, url.id, new Date(), html], (err, result) => {
                //     if (err) {
                //       log(err);
                //     }
                //     resolve()
                //   })
                // }))
                words.forEach(word => {
                    if (html.indexOf(word.word) == -1)
                        return
                    promiseList.push(new Promise(resolve => {
                        zoroDB.query('select count(*) from url_word where url=? and word=?', [url.id, word.id], (err, rows, fields) => {
                            if (err) {
                                logger.error('[' + __filename + ':' + __line + ']', err)
                                resolve()
                                return
                            }
                            if (rows[0]['count(*)'] > 0) {
                                resolve()
                                return
                            }
                            zoroDB.query('insert into url_word(url, word, p) values(?, ?, 0.01)', [url.id, word.id], (err, result) => {
                                if (err) {
                                    logger.error('[' + __filename + ':' + __line + ']', err)
                                    resolve()
                                    return
                                }
                                resolve()
                            })
                        })
                    }))
                })
                Promise.all(promiseList).then(result => {
                    isDoing = false;
                    if (result[0]) {
                        exports.start()
                    } else {
                        if (typeof require != 'undefined' && require.main == module) {
                            process.exit()
                        }
                    }
                }).catch(err => {
                    logger.error('[' + __filename + ':' + __line + ']', err)
                })
            })
        }, result => {
            var title = '获取title失败'
            logger.debug('[' + __filename + ':' + __line + ']', 'url = ' + url.url, 'title = ' + title)
            zoroDB.query('update url set title=? where id=?', [title, url.id], (err, result) => {
                if (err) {
                    logger.error('[' + __filename + ':' + __line + ']', err)
                }
                isDoing = false
                if (!url.title) {
                    exports.start()
                } else {
                    if (typeof require != 'undefined' && require.main == module) {
                        process.exit()
                    }
                }

            })
        })
    }).catch(err => {
        logger.error('[' + __filename + ':' + __line + ']', err)
    })
}

if (typeof require != 'undefined' && require.main == module) {
    require('../util/util')
    exports.start()
}